package com.museum.controller;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.museum.common.lang.Result;
import com.museum.entity.Thesis;
import com.museum.service.IThesisService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;


/**
 * @author Akihi
 * @create 2023/01/07 20:40
 */
@RestController
@Slf4j
@RequestMapping("sys/thesis")
public class ThesisController {
    @Autowired
    private IThesisService thesisService;
    /*根据id查询*/
    @GetMapping("info/{id}")
    public Result info(@PathVariable("id") Long id){
        Thesis thesis = thesisService.getById(id);
        return Result.success(thesis);
    }
    /*分页查询，不查询正文字段*/
    @GetMapping("list")
    public Result list(String title, Long current, Long size){
        Page<Thesis> pageData = thesisService.page(
                new Page<>(current, size),
                new QueryWrapper<Thesis>()
                        /*指定除了正文字段外都查询*/
                        .select(Thesis.class, item -> !"body".equals(item .getColumn()))
                        .like(StrUtil.isNotBlank(title), "title", title)
        );
        return Result.success(pageData);
    }
    /*添加新论文*/
    @Transactional(rollbackFor = Exception.class)
    @PostMapping("save")
    public Result save(Thesis thesis){

        boolean isSuccess = thesisService.save(thesis);
        if (!isSuccess){
            return Result.fail("保存失败！请稍后重试");
        }
        return Result.success("保存成功！");
    }
    /*更新论文*/
    @Transactional(rollbackFor = Exception.class)
    @PostMapping("update")
    public Result update(Thesis thesis){
        boolean isSuccess = thesisService.updateById(thesis);
        if (!isSuccess){
            return Result.fail("保存失败！请稍后重试");
        }
        return Result.success("保存成功！");
    }
    /*删除论文*/
    @Transactional(rollbackFor = Exception.class)
    @PostMapping("delete")
    public Result delete(@RequestBody Long[] ids){
        boolean isSuccess = thesisService.removeByIds(Arrays.asList(ids));
        if (!isSuccess){
            return Result.fail("删除失败！请稍后重试");
        }
        return Result.success("删除成功！");
    }


}
